using System;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;

namespace AntEater.Runtime.Logging
{
    /// <summary>
    /// A trace listeneer for the Enterprise Library
    /// </summary>
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class OutputTraceListener : CustomTraceListener
    {
        /// <summary>
        /// Writes trace information, a data object and event information to the listener specific output.
        /// </summary>
        /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"></see> object that contains the current process ID, thread ID, and stack trace information.</param>
        /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
        /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType"></see> values specifying the type of event that has caused the trace.</param>
        /// <param name="id">A numeric identifier for the event.</param>
        /// <param name="data">The trace data to emit.</param>
        /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode"/></PermissionSet>
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {
            // Check method parameters
            if (data == null) {
                throw new ArgumentNullException("data");
            }

            if (this.Formatter != null) {
                this.WriteLine(this.Formatter.Format(data as LogEntry));
            } else {
                this.WriteLine(data.ToString());
            }
        }

        /// <summary>
        /// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
        /// </summary>
        /// <param name="message">A message to write.</param>
        public override void Write(string message) {
            this.WriteLine(message);
        }

        /// <summary>
        /// Writes a message to the output 
        /// </summary>
        /// <param name="message">The string to write to the output</param>
        public override void WriteLine(string message) {
            AntEaterRuntime.Instance.Output.WriteLine(message);
        }
    }
}
